package com.hehe.httpurlconnectiontest2;

import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.graphics.BitmapFactory;
import android.graphics.BitmapRegionDecoder;
import android.icu.text.LocaleDisplayNames;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.net.URL;
import java.security.cert.TrustAnchor;
import java.util.LinkedList;
import java.util.Objects;
import java.util.regex.Pattern;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    private TextView Return,      //返回
                     UserStatus;  //用户
    private FrameLayout frameLayout;
    private DevicesFragment devicesFragment = null;//设备页面
    private LinkedList<SensorsFragment> sensorsFragmentList = new LinkedList<SensorsFragment>();//储存传感器页面的listview
    private FragmentManager fManager;

    //TODO 这里之后要加入登录程序
    private String UserName = "hehe001";//用户名
    private String password = "hh1593572486";//账号密码
    private String myApiKey = "86d085fda02db25d2b48f25f5d9c7b8c";//apikey
    private User user = new User(UserName,password,myApiKey);
    private LinkedList<YeelinkDecives> yeelinkDecivesList = new LinkedList<YeelinkDecives>();//储存所有设备数据的列表

    //线程
    private initDevicesThread thread;
    private FlashDataThread flashDataThread;
    boolean flag1 = true;//用于设备信息获取线程的循环
    boolean flag2 = true;//用于数据更新线程
    boolean flag3 = false;//用于设备页面ListView的点击事件，第一次进入app，在设备信息和数据没有加载好前，点击设备是不会进入传感器页面的

    //这个handler用于线程与主线程通信
    public Handler handler = new Handler(){
        public void handleMessage(Message msg){
            String buffer ;//
            switch (msg.what){

                case 0x000://这个用来处理线程中需要Toast的情况
                    Log.i("handler 0",msg.obj.toString());
                    //handler中不能直接使用Toast
                    Looper.prepare();
                    Toast.makeText(MainActivity.this,msg.obj.toString(),Toast.LENGTH_SHORT).show();
                    Looper.loop();
                    break;
                case 0x001://将apikey 解析出来

                     buffer = JSONData.getApiKey((String)msg.obj);
                    if (buffer=="10000"){
                        Looper.prepare();
                        Toast.makeText(MainActivity.this,"用户名或密码错误",Toast.LENGTH_SHORT).show();
                        Looper.loop();
                    }else  if (buffer =="500"){
                        Looper.prepare();
                        Toast.makeText(MainActivity.this,"服务器异常",Toast.LENGTH_SHORT).show();
                        Looper.loop();
                    }
                    else {
                        user.setApiKey(buffer);
                        Log.i("U-ApiKey:",user.getApiKey());
                    }
                    break;

                case 0x002://显示设备列表页面
                    FragmentTransaction fTransaction  = fManager.beginTransaction();
                    if (devicesFragment==null){
                        devicesFragment = new DevicesFragment(yeelinkDecivesList,flag3);
                        fTransaction.add(R.id.myFrameLayout,devicesFragment);
                    }else{
                        devicesFragment.flash();
                    }

                    fTransaction.commit();

                    break;
                case 0x003:
                    Log.i("handler","getSensorList");
                    for (YeelinkDecives i : yeelinkDecivesList){
                        for (YeelinkSensor j : i.getSensorLinkedList()){
                            Log.i("sensor id",j.getSensor_id());
                            Log.i("sensor title",j.getSensor_title());
                            Log.i("sensor about",j.getSensor_about());
                        }
                    }
                    break;
                case 0x004:

            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        fManager = getFragmentManager();

        Return = (TextView)findViewById(R.id.Return);
        UserStatus = (TextView)findViewById(R.id.UserStatus);
        frameLayout = (FrameLayout)findViewById(R.id.myFrameLayout);

        Return.setOnClickListener(this);
        UserStatus.setOnClickListener(this);

        //将Return隐藏
        Return.setVisibility(View.INVISIBLE);

        //设备信息获取线程
        thread = new initDevicesThread();
        thread.start();
    }

    //销毁MainActivity时执行
    @Override
    protected void onDestroy() {
        super.onDestroy();
        //如果服务器有问题导致了initDevicesList线程一直循环，通过flag终止，直接退出app还是会在后台执行，线程并不会在销毁MainActivity时销毁
        flag1 = false;
        flag2 = false;
    }

    //点击事件
    @Override
    public void onClick(View v){
        FragmentTransaction fTransaction = fManager.beginTransaction();
        switch (v.getId()){
            case R.id.Return:
                //点击返回，退回到设备页面
                Log.i("Return","Click!");
                if (devicesFragment!=null) {
                    hideAllFragment(fTransaction);
                    fTransaction.show(devicesFragment);
                }
                //将Return隐藏
                Return.setVisibility(View.INVISIBLE);
                break;
            case R.id.UserStatus:
                //TODO 用户登录点击方法，之后再解决
                break;
            default:
                break;
        }
        fTransaction.commit();
    }

    //从Yeelink获取ApiKey
    //TODO 这个用于之后的登录程序
    public void getApiKey(){
        new Thread(){
            String jsondata;
            @Override
            public void run() {
                super.run();
                try {
                    jsondata = GetDataFromYeelink.getApiKey(user);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                // 用一个hander进行与UI的交互
                Message msg = new Message();
                msg.obj = jsondata;
                msg.what = 1;
                handler.handleMessage(msg);
                Log.i("GetApiKey:",jsondata);
            }
        }.start();
    }

    //设备信息初始化获取过程线程
    public class initDevicesThread extends Thread{
        @Override
        public void run() {
            super.run();
            //初始化过程中如果出现服务器的异常，则反复请求响应
            flag1 = true;
            String jsondata = null;//传回的json数据
            //如果用于网络或者服务器的问题，未能正确获取需要数据,使用正则表达式匹配http返回码
            String patter1 = "5\\d\\d";//服务器问题以5开头
            String patter2 = "4\\d\\d";//手机自己的问题以4开头

            Log.i("initDevicss","开始循环");

            while (flag1) {
                try {
                    //等待2秒
                    sleep(2000);
                    Log.i("initDevices", "开始获取数据");
                    //从服务器获取json数据
                    jsondata = GetDataFromYeelink.listDevices(user.getApiKey());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (Pattern.matches(patter1,jsondata)) {//匹配http状态码，以5开头，服务器异常
                    Log.i("Http responde code", jsondata);
                    //这里用handler在UI线程中使用Toast，但是发现使用后会出现循环在这里停止的现象
                    //我认为是在handler中使用Looper.loop()的缘故，直接改用runOnUiThread()方法解决
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(MainActivity.this,"服务器异常",Toast.LENGTH_SHORT).show();
                        }
                    });

                    flag1 = true;
                    //等待10s，再重新请求
                    try {
                        sleep(10000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } else if (Pattern.matches(patter2,jsondata)) {//匹配http状态码，以4开头，为客户端问题
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(MainActivity.this,"请检查网络连接",Toast.LENGTH_SHORT).show();
                        }
                    });
                    //如果是客户端的问题，就中止循环
                    flag1 = false;

                } else {
                    Log.i("initDevicesThread","成功获取设备列表");
                    yeelinkDecivesList = JSONData.getDevicesList(jsondata);
                    for (YeelinkDecives i : yeelinkDecivesList) {
                        Log.i("device id", i.getDevice_id());
                        Log.i("device title", i.getDevice_title());
                        Log.i("device about", i.getDevece_about());
                    }
                    // 用一个hander进行设备页面显示
                    Message msg = new Message();
                    msg.obj = jsondata;
                    msg.what = 2;
                    handler.handleMessage(msg);

                    //获取每个设备的传感器
                    try {
                        if (yeelinkDecivesList != null && user != null) {
                            for (int i = 0; i < yeelinkDecivesList.size(); i++) {
                                LinkedList<YeelinkSensor> list = JSONData.getSensorsList(GetDataFromYeelink.listSensors(user.getApiKey(), yeelinkDecivesList.get(i).getDevice_id()));
                                yeelinkDecivesList.get(i).setSensorLinkedList(list);
                                for (int j = 0;j<list.size();j++){
                                    JSONData.getSensorInfo(list.get(j),GetDataFromYeelink.checkSensor(user.getApiKey(),yeelinkDecivesList.get(i).getDevice_id(),list.get(j).getSensor_id()));
                                    Log.i("get sensor info",list.get(j).getUnit_symbol());
                                }
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    //handler.sendEmptyMessage(0x003);
                    //传感器的基本信息更新完成后，开始数据更新线程
                    flashDataThread = new FlashDataThread();
                    flashDataThread.start();
                    //响应成功后，退出循环
                    flag1 = false;
                }
                Log.i("initDevicesThread loop","loop over");
            }
        }
    }

    //隐藏所有的Fragment
    private void hideAllFragment(FragmentTransaction fragmentTransaction){
        if (devicesFragment!=null){
            fragmentTransaction.hide(devicesFragment);
        }
        if (sensorsFragmentList!=null){
            for (int i = 0;i < sensorsFragmentList.size();i++){
                fragmentTransaction.hide(sensorsFragmentList.get(i));
            }
        }
    }

    //DevicesFragment中的ListView点击后的方法，根据点击的那一项去显示传感器页面
    public void showSensorFragment(int position){

        YeelinkDecives decives = yeelinkDecivesList.get(position);
        Log.i("device title",decives.getDevice_title());
        if (decives.getSensorLinkedList().size()==0){
            Log.i("SensorList","null");
        }else {
            for (YeelinkSensor j : decives.getSensorLinkedList()){
                Log.i("sensor id",j.getSensor_id());
                Log.i("sensor title",j.getSensor_title());
                Log.i("sensor about",j.getSensor_about());
                Log.i("sensor symbol",j.getUnit_symbol());
                Log.i("sensor symbol",j.getDataPoint().getValue());
            }
        }

        handler.sendEmptyMessage(3);

        FragmentTransaction fTransaction = fManager.beginTransaction();
        //隐藏所有的页面
        hideAllFragment(fTransaction);

        if (decives.getSensorFragmentPosition() == 100 || decives.getSensorFragmentPosition()>=sensorsFragmentList.size()){//如果点击的设备的传感器页面还没建立，新建后加入页面管理列表
            //在设备类中参数SensorFragmentPosition，这个参数代表了这个设备指向的传感器页面储存在传感器管理表中的位置
            decives.setSensorFragmentPosition(sensorsFragmentList.size());
            //建立新页面
            SensorsFragment sensorsFragment = new SensorsFragment(yeelinkDecivesList,position);
            //加入管理列表
            sensorsFragmentList.addLast(sensorsFragment);
            //显示
            fTransaction.add(R.id.myFrameLayout,sensorsFragmentList.getLast());
        }else{
            //显示
            fTransaction.show(sensorsFragmentList.get(yeelinkDecivesList.get(position).getSensorFragmentPosition()));
        }
        Return.setVisibility(View.VISIBLE);
        fTransaction.commit();
    }

    //刷新所有的Fragment
    public void flashAllFragment(){
        FragmentTransaction fTransaction = fManager.beginTransaction();
        if (sensorsFragmentList!=null) {
            for (int i = 0; i < sensorsFragmentList.size(); i++) {
                sensorsFragmentList.get(i).flash();
            }
        }
        fTransaction.commit();
    }

    //数据点更新线程，在初始化后就一直执行
    public class FlashDataThread extends Thread{
        YeelinkDecives decivesbuffer;
        YeelinkSensor sensorbuffer;
        @Override
        public void run() {
            super.run();
            //如果用于网络或者服务器的问题，未能正确获取需要数据,使用正则表达式匹配错误码
            String patter1 = "5\\d\\d";//服务器问题以5开头
            String patter2 = "4\\d\\d";//手机自己的问题以4开头
            while(flag2){

                if (yeelinkDecivesList!=null){
                    //设备列表不为空
                    for (int i = 0;i<yeelinkDecivesList.size();i++){
                        //获取设备
                        decivesbuffer = yeelinkDecivesList.get(i);
                        if (decivesbuffer.getSensorLinkedList()!=null){
                            //设备的传感器列表不为空
                            for (int j = 0;j<decivesbuffer.getSensorLinkedList().size();j++){
                                //获取传感器
                                sensorbuffer = decivesbuffer.getSensorLinkedList().get(j);
                                //josn数据
                                String json = GetDataFromYeelink.listDatapoint(user.getApiKey(),decivesbuffer.getDevice_id(),sensorbuffer.getSensor_id());

                                if (Pattern.matches(patter1,json)){
                                    Log.i("FlashDataThread","服务器异常");

                                }else if(Pattern.matches(patter2,json)){
                                    Log.i("FlashDataThread","客户端问题");
                                    Log.i("devices id",decivesbuffer.getDevice_id());
                                    Log.i("devices id",sensorbuffer.getSensor_id());

                                }else {
                                    //从json数据中获取数据点
                                    sensorbuffer.setDataPoint(JSONData.getDataPoint(json));
                                    Log.i("testFlashDataThread", sensorbuffer.getDataPoint().getValue());
                                    if (devicesFragment!=null){
                                        devicesFragment.setFlag3(true);
                                    }
                                    //更新页面
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            flashAllFragment();
                                        }
                                    });
                                }
                            }
                        }
                    }
                }
                try {
                    sleep(10000);//每十秒执行一次
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
